package com.doodle.common.drawable;

import android.graphics.drawable.Drawable;

import com.doodle.common.data.AsyncResource;
import com.doodle.common.data.DataAdapter;

public abstract class MeasuredAsyncDrawable extends AsyncDrawable {

	public static final int DRAWABLE_TYPE_ICON = 0;
	public static final int DRAWABLE_TYPE_THUMB = 1;
	public static final int DRAWABLE_TYPE_IMAGE = 2;

	protected final int mFitMode;
	protected final int mType;
	
	protected int mMeasuredWidth;
	protected int mMeasuredHeight;
	
	public MeasuredAsyncDrawable(int measuredWidth, int measuredHeight, int fitMode, int type,
								 AsyncResource.JobExecutor<Drawable> jobExecutor, Drawable placeHolder, int id, DataAdapter.DataLoadedListener listener) {
		super(jobExecutor, placeHolder, id, listener);
		mFitMode = fitMode;
		mType = type;
		mMeasuredWidth = measuredWidth;
		mMeasuredHeight = measuredHeight;
	}
	
	public void measure(int maxSize) {	}
	
	public void measure(int width, int height, int maxSize, boolean fixedHeightToMax, float limitRation) {
		if (fixedHeightToMax) {
			mMeasuredWidth = calcMeasuredLength(width, height, maxSize, limitRation);
			mMeasuredHeight = maxSize;
		} else {
			mMeasuredWidth= maxSize;
			mMeasuredHeight = calcMeasuredLength(height, width, maxSize, limitRation);
		}
	}
	
	public static int calcMeasuredLength(int lengthToFixed, int lengthToCalc, int maxSize, float limitRatio) {
		if (lengthToFixed != 0 && lengthToCalc != 0) {
			if (lengthToFixed == lengthToCalc) {
				return maxSize;
			}
			final float ratio = (float)lengthToFixed / (float)lengthToCalc;
    		if (ratio > limitRatio) {
    			lengthToFixed = Math.round(lengthToCalc * limitRatio);
        	} else if (ratio < (1f / limitRatio)) {
        		lengthToCalc = Math.round(lengthToFixed * limitRatio);
        	}
    		return Math.round(maxSize * lengthToFixed / (float)lengthToCalc);
		} else {
			return maxSize;
		}
	}
	
	public int getMeasuredWidth() {
		return mMeasuredWidth;
	}
	
	public int getMeasuredHeight() {
		return mMeasuredHeight;
	}
	
	public int getType() {
		return mType;
	}

	@Override
	public int getIntrinsicWidth() {
		return mMeasuredWidth == 0 ? super.getIntrinsicWidth() : mMeasuredWidth;
	}

	@Override
	public int getIntrinsicHeight() {
		return mMeasuredHeight == 0 ? super.getIntrinsicHeight() : mMeasuredHeight;
	}
}
